import VuiElement from '../../base/element';
import { createEle } from '../../dom';
import './style.css';

export default class VuiTable extends VuiElement {
  constructor(config = { columns: [], dataSource: [] }) {
    super();
    this.className = 'vui-table';
    const defaultConfig = {};
    Object.assign(this._config, defaultConfig, config);
  }

  initUI() {
    this.container = createEle('table', { className: this.className });
    this.append([this.createTHead(), this.createTBody()]);
  }

  createTHead() {
    const config = this._config;
    const thead = createEle('thead', { className: 'vui-table-head' });
    const tr = createEle('tr');
    config.columns.forEach(item => {
      tr.appendChild(createEle('th', { innerText: item.title, id: item.dataIndex }));
    });

    thead.appendChild(tr);
    return thead;
  }

  createTBody() {
    const config = this._config;
    const tbody = createEle('tbody');
    config.dataSource.forEach(data => {
      const tr = createEle('tr');
      config.columns.forEach(col => {
        Object.keys(data).forEach(key => {
          if (key === col.dataIndex) {
            if (key === 'action') {
              const td = createEle('td');
              td.appendChild(data[key]);
              tr.appendChild(td);
              return;
            }
            tr.appendChild(createEle('td', { innerText: data[key] }));
          }
        });
      });
      tbody.appendChild(tr);
    });
    return tbody;
  }

  /**
   * 创建新实例 并执行initUI函数
   * columns和dataSource格式要求：
   * columns: [
   *  { title: 'xxxx', dataIndex: 'key1' },
   *  { title: 'xxxx', dataIndex: 'key2' },
   *  { title: 'xxxx', dataIndex: 'key3' },
   * ];
   * dataSource: [
   *  { key1: 'xxx', key2: 'xxx', key3: 'xxx' },
   *  { key1: 'xxx', key2: 'xxx', key3: 'xxx' },
   * ]
   */
  static newInstance(config = { columns: [], dataSource: [] }) {
    const instance = new VuiTable(config);
    instance.initUI();
    return instance;
  }
}
